package com.tq68.weixin.controller.checkin;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.tq68.weixin.model.Checkin;
import com.tq68.weixin.model.CoinsLog;
import com.tq68.weixin.model.Community;
import com.tq68.weixin.model.CommunityAlias;
import com.tq68.weixin.model.User;
import com.tq68.weixin.model.UserCommunity;
import com.tq68.weixin.utils.DateUtils;
import com.tq68.weixin.utils.JssdkParamUtil;
import com.tq68.weixin.vo.JssdkVO;
import com.tq68.weixin.vo.UserVO;

public class CheckinController extends Controller {

	public void index(){
		render("index.html");
	}
	
	public void selectcommunity(){
		Integer fromAddBbs = getParaToInt("fromAddBbs",0);
		JssdkParamUtil jpu = new JssdkParamUtil();
		String urlStr = getRequest().getRequestURL().toString();
		if(urlStr.indexOf("?")>-1){
			urlStr = urlStr.substring(0,urlStr.indexOf("?"));
		}
		System.out.println("urlStr="+urlStr);
		JssdkVO jssdk = jpu.getWebParam(urlStr);
		if(jssdk.getErrorMsg()==null){
			setAttr("noncestr", jssdk.getNonceStr());
	        setAttr("timestamp", jssdk.getTimestamp());
	        setAttr("signature",jssdk.getSignature());
			setAttr("appId", PropKit.get("appId"));
	        setAttr("baiduAK", PropKit.get("baiduAK"));
		}else{
			setAttr("errorMsg",jssdk.getErrorMsg());
		}
		setAttr("fromAddBbs",fromAddBbs);
		render("selectcommunity.html");
	}
	
	//GPS坐标转百度坐标
	public void toBaiduMap(){
		String longitude = getPara("longitude");
		String latitude = getPara("latitude");
		String url = "http://api.map.baidu.com/geoconv/v1/?coords="+longitude+","+latitude+";"+longitude+","+latitude+"&from=1&to=5&ak="+PropKit.get("baiduAK");
		String json = HttpKit.get(url);
		renderText(json);
	}
	@Before(Tx.class)
	public void doCheckin(){
		String commName = getPara("commName");
//		String commAddress = getPara("commAddress");
		String longitude = getPara("lng");
		String latitude = getPara("lat");
		UserVO uservo = getSessionAttr("uservo");

		//根据小区别名或标准名判断是否已设置此小区
		Community comm = Community.dao.getCommunityByAlias(commName);
		UserCommunity uc = UserCommunity.dao.findById(uservo.getUsercommid());
//		if(comm==null){
//			comm = new Community();
//			comm.setCommName(commName);
//			comm.setCommAddress(commAddress);
//			comm.save();
//			CommunityAlias alias = new CommunityAlias();
//			alias.setAlias(commName);
//			alias.setAliasAddress(commAddress);
//			alias.setCommid(comm.getId());
//			alias.save();
//		}
		if(uc==null){
			//添加业主与小区关联关系表
			uc = new UserCommunity();
			uc.setUserid(uservo.getUserid());
			uc.setCommunityid(comm.getId());
			uc.save();
		}
		//添加用户的打卡信息
		Checkin ch = new Checkin();
		ch.setLatitude(latitude);
		ch.setLongitude(longitude);
		ch.setCheckCommid(comm.getId());
		ch.setCheckCommname(comm.getCommName());
		ch.setCheckAliasCommid(CommunityAlias.dao.getCommunityAliasByAlias(commName).getId());
		ch.setCheckAliasCommname(commName);
		ch.setChecktime(DateUtils.toTimeStr(new Date()));
		ch.setNickname(uservo.getNickname());
		ch.setUserid(uservo.getUserid());
		ch.setUsercommid(uc.getId());
		ch.save();
		//更新用户表的小区信息和最后打卡日期，目前一个用户只属于一个小区
		User user = User.dao.findById(uservo.getUserid());
		user.setUserCommId(comm.getId());
		user.setUserCommName(comm.getCommName());
		user.setLastCheckinDate(DateUtils.toDateStr(new Date()));
		user.update();
		//更新周周期开始时间，周周期打卡次数以及总打卡次数
		uc.setCheckinWeekCount((uc.getCheckinWeekCount()!=null?uc.getCheckinWeekCount():0)+1);
		uc.setCheckinTotalCount((uc.getCheckinTotalCount()!=null?uc.getCheckinTotalCount():0)+1);
		if(uc.getCheckinWeekTime()==null){
			uc.setCheckinWeekTime(DateUtils.toTimeStr(new Date()));
		}
		uc.update();
		//如果是用户第一次打卡，更新信息到session
		if(uservo.getUserCommunityId()==null){
			uservo.setUserCommunityId(comm.getId());
			uservo.setUserCommunityName(comm.getCommName());
			uservo.setUsercommid(uc.getId());
		}
		uservo.setLastCheckinDate(user.getLastCheckinDate());
		uservo.setCheckinToday(DateUtils.toDateStr(new Date()).equals(user.getLastCheckinDate())?true:false);
		//打卡完成之后，更新最近的打卡记录
		List<Checkin> checklist = uservo.getRecentlyChecklist();
		if(checklist!=null && !checklist.isEmpty() && checklist.size()==3){
			checklist.remove(checklist.size()-1);
		}else{
			checklist = new ArrayList<Checkin>();
		}
		checklist.add(0, ch);
		uservo.setRecentlyChecklist(checklist);
		setSessionAttr("uservo", uservo);
		renderText("OK");
	}
	
	public void userLevel(){
		
	}
	
	public void userCoins(){
		
	}
	
	public void userCoinsDetail(){
		UserVO uservo = getSessionAttr("uservo");
		setAttr("datalist",CoinsLog.dao.getCoinsList(uservo.getUserid()));
		render("userCoinsDetail.html");
	}
	
	public void userCoinsGet(){
		
	}
	
	public void userGift(){
		
	}
	
	public void userGiftHistory(){
		
	}
	
	public void edit(){
		setAttr("user",User.dao.findById(getParaToInt("userid",0)));
		render("edit.html");
	}
	
	public void editEntity(){
		String oldHomeTown = getPara("oldHomeTown","");
		boolean homeTownChange = false;
		User user = getBean(User.class);
		if(user.getHomeTownTimes()>0 && !oldHomeTown.equals(user.getHomeTown())){
			user.setHomeTownTimes(user.getHomeTownTimes()-1);
			homeTownChange = true;
		}
		user.update();
		//更新session
		UserVO uservo = getSessionAttr("uservo");
		uservo.setNickname(user.getNickname());
		uservo.setSex(user.getSex());
		if(homeTownChange){
			uservo.setHomeTown(user.getHomeTown());
			uservo.setProvince();
			uservo.setCity();
			uservo.setDistin();
		}
		setSessionAttr("uservo", uservo);
		redirect("/checkin");
	}
	
}
